import React, { useEffect, useState } from 'react';
import {
  Button,
  Grid,
  Input,
  Link,
  Message,
  Popconfirm,
  Popover,
  Space,
  Tree,
} from '@arco-design/web-react';
import {
  IconAlignLeft,
  IconDelete,
  IconPlus,
} from '@arco-design/web-react/icon';
import {
  addCollegeOrMajorApi,
  delCollegeOrMajorApi,
  editCollegeOrMajorApi,
} from '@/request/api';
const Col = Grid.Col;
const Row = Grid.Row;

function OrganizationTree({
  copyTreeData,
  treeData,
  setTreeData,
  getSelectedInfo,
}) {
  const [inputValue, setInputValue] = useState('');
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState('');
  const [edit, setEdit] = useState(false);

  useEffect(() => {
    if (!inputValue) {
      setTreeData(copyTreeData);
    } else {
      const result = searchData(inputValue);
      setTreeData(result);
    }
  }, [inputValue]);

  const searchData = (inputValue) => {
    const loop = (data) => {
      const result = [];
      data.forEach((item) => {
        if (item.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1) {
          result.push({ ...item });
        } else if (item.children) {
          const filterData = loop(item.children);

          if (filterData.length) {
            result.push({ ...item, children: filterData });
          }
        }
      });
      return result;
    };

    return loop(treeData);
  };

  const closePopover = () => {
    for (const collage of treeData) {
      collage['visible'] = false;
      collage['visiblePlus'] = false;
      for (const major of collage.children) {
        major['visible'] = false;
        major['visiblePlus'] = false;
      }
    }
  };

  const clickEdit = () => {
    const newEdit = !edit;
    if (newEdit) {
      closePopover();
      setVisible(false);
      setTreeData(treeData);
    }
    setEdit(newEdit);
  };

  const clickAddTreeNode = (node) => {
    if (node.dataRef.inputValue.length !== 0) {
      const info = {
        name: node.dataRef.inputValue,
        parentId: node.dataRef.id,
      };
      addCollegeOrMajorApi(info)
        .then((res) => {
          const { data, msg } = res;
          node.dataRef.visiblePlus = false;
          setTreeData([...treeData]);
          Message.success(msg);
          window.location.reload();
        })
        .catch((e) => {
          console.log(e);
        });
    } else {
      Message.error('输入框不能为空!');
    }
  };

  const clickAddCollege = () => {
    if (value.length !== 0) {
      addCollegeOrMajorApi({ name: value })
        .then((res) => {
          const { msg } = res;
          Message.success(msg);
          window.location.reload();
        })
        .catch((e) => {
          console.log(e);
        });
    } else {
      Message.error('输入框不能为空!');
    }
  };

  const clickEditTreeNode = (node) => {
    if (node.dataRef.inputValue.length !== 0) {
      const info = {
        id: node.dataRef.id,
        name: node.dataRef.inputValue,
      };
      editCollegeOrMajorApi(info)
        .then((res) => {
          const { data, msg } = res;
          node.dataRef.visible = false;
          setTreeData([...treeData]);
          Message.success(msg);
          window.location.reload();
        })
        .catch((e) => {
          console.log(e);
        });
    } else {
      Message.error('输入框不能为空!');
    }
  };

  const clickDelTreeNode = (node) => {
    const info = {
      id: node.dataRef.id,
    };
    delCollegeOrMajorApi(info)
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        window.location.reload();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  return (
    <Col span={4}>
      <Input.Search
        style={{
          marginBottom: 8,
          marginTop: 8,
          maxWidth: 240,
        }}
        onChange={setInputValue}
      />
      <Space wrap={true}>
        <Button type="outline" size={'small'} onClick={() => clickEdit()}>
          {edit ? '取消编辑' : '架构编辑'}
        </Button>
        {/*<Button type="outline" size={'small'}>*/}
        {/*  查看架构图*/}
        {/*</Button>*/}
      </Space>
      <Row justify={'space-between'} align={'center'}>
        <h4>学校架构</h4>
        {edit ? (
          <Popover
            title="增加学院"
            popupVisible={visible} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
            content={
              <span>
                <Input
                  allowClear
                  placeholder={`学院名称`}
                  onChange={(value) => {
                    setValue(value);
                  }}
                />
                <Space align={'end'} style={{ marginTop: 10 }}>
                  <Link
                    onClick={() => {
                      setVisible(false);
                    }}
                  >
                    取消
                  </Link>
                  <Link
                    onClick={() => {
                      clickAddCollege();
                    }}
                  >
                    增加
                  </Link>
                </Space>
              </span>
            }
          >
            <Button
              size={'small'}
              icon={<IconPlus />}
              style={{
                fontSize: 12,
                color: '#3370ff',
                backgroundColor: '#ffffff',
              }}
              onClick={() => {
                setVisible(true);
              }}
            ></Button>
          </Popover>
        ) : (
          <div></div>
        )}
      </Row>
      <Tree
        treeData={treeData}
        fieldNames={{
          key: 'id',
          title: 'name',
          children: 'children',
        }}
        onSelect={(keys, extra) => {
          const selectedInfo = {
            majorId: extra.node.props.dataRef.id,
            collegeId: extra.node.props.dataRef.parentId,
            major: extra.node.props.dataRef.name,
          };
          console.log(selectedInfo, 'selectedInfo');
          getSelectedInfo(selectedInfo);
        }}
        renderTitle={({ title }) => {
          if (inputValue) {
            const index = title
              .toString()
              .toLowerCase()
              .indexOf(inputValue.toLowerCase());

            if (index === -1) {
              return title;
            }

            const prefix = title.toString().substr(0, index);
            const suffix = title.toString().substr(index + inputValue.length);
            return (
              <span>
                {prefix}
                <span style={{ color: 'var(--color-primary-light-4)' }}>
                  {title.toString().substr(index, inputValue.length)}
                </span>
                {suffix}
              </span>
            );
          }
          return title;
        }}
        renderExtra={(node) => {
          if (edit) {
            return (
              <div>
                {node.dataRef.type === 0 ? (
                  <Popover
                    title="增加专业"
                    popupVisible={node.dataRef.visiblePlus} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                    content={
                      <span>
                        <Input
                          allowClear
                          placeholder={`专业名称`}
                          onChange={(value) => {
                            node.dataRef.inputValue = value;
                          }}
                        />
                        <Space align={'end'} style={{ marginTop: 10 }}>
                          <Link
                            onClick={() => {
                              node.dataRef.visiblePlus = false;
                              setTreeData([...treeData]);
                            }}
                          >
                            取消
                          </Link>
                          <Link
                            onClick={() => {
                              clickAddTreeNode(node);
                            }}
                          >
                            增加
                          </Link>
                        </Space>
                      </span>
                    }
                  >
                    <Button
                      size={'mini'}
                      style={{
                        position: 'absolute',
                        right: 50,
                        fontSize: 12,
                        top: 5,
                        color: '#3370ff',
                        backgroundColor: '#ffffff',
                      }}
                      icon={<IconPlus />}
                      onClick={() => {
                        closePopover();
                        node.dataRef.visiblePlus = true;
                        setTreeData([...treeData]);
                      }}
                    ></Button>
                  </Popover>
                ) : null}

                <Popover
                  title="修改"
                  popupVisible={node.dataRef.visible} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                  content={
                    <span>
                      <Input
                        allowClear
                        placeholder={`${node.dataRef.name}`}
                        onChange={(value) => {
                          node.dataRef.inputValue = value;
                        }}
                      />
                      <Space align={'end'} style={{ marginTop: 10 }}>
                        <Link
                          onClick={() => {
                            node.dataRef.visible = false;
                            setTreeData([...treeData]);
                          }}
                        >
                          取消
                        </Link>
                        <Link
                          onClick={() => {
                            clickEditTreeNode(node);
                          }}
                        >
                          修改
                        </Link>
                      </Space>
                    </span>
                  }
                >
                  <Button
                    size={'mini'}
                    style={{
                      position: 'absolute',
                      right: 30,
                      fontSize: 12,
                      top: 5,
                      color: '#3370ff',
                      backgroundColor: '#ffffff',
                    }}
                    icon={<IconAlignLeft />}
                    onClick={() => {
                      closePopover();
                      node.dataRef.visible = true;
                      setTreeData([...treeData]);
                    }}
                  ></Button>
                </Popover>

                <Popconfirm
                  focusLock
                  icon={null}
                  title="确定删除吗?"
                  onOk={() => {
                    clickDelTreeNode(node);
                  }}
                >
                  <Button
                    style={{
                      position: 'absolute',
                      right: 6,
                      fontSize: 12,
                      top: 5,
                      color: '#3370ff',
                      backgroundColor: '#ffffff',
                    }}
                    size={'mini'}
                    icon={<IconDelete />}
                    onClick={() => {
                      closePopover();
                      setTreeData([...treeData]);
                    }}
                  ></Button>
                </Popconfirm>
              </div>
            );
          }
          return null;
        }}
      ></Tree>
    </Col>
  );
}

export default OrganizationTree;
